﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace Test4SerailPort
{
    public partial class Form1 : Form
    {
        //  Create a Serial Port object
        SerialPort sp = new SerialPort();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            sp.BaudRate = 57600;
            sp.DataBits = 8;
            sp.Parity = Parity.None;
            sp.PortName = "COM1";
            sp.StopBits = StopBits.One;

            sp.Open();
            sp.ReadTimeout = 500;

            sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
        }

        void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string message = sp.ReadExisting();
            System.Diagnostics.Debug.WriteLine(message);
            sp.Write(message[0].ToString());
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                sp.WriteLine(textBox1.Text);
                textBox1.Text = string.Empty;
            }
            catch (Exception ex)
            {
                label1.Text = ex.Message;
            }
        }
    }
}
